import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
	{
		path: '/login',
		name: 'Login',
		component: () =>
			import(/* webpackChunkName: "about" */ '../views/Login.vue')
	},
	{
		path: '/blogs',
		name: 'Blogs',
		component: () =>
			import(/* webpackChunkName: "about" */ '../views/Blogs.vue')
	},
	{
		path: '/admin',
		name: 'Admin',
		component: () =>
			import(/* webpackChunkName: "about" */ '../views/adminLogin.vue')
	},
	{
		path: '/home',
		name: 'Home',
		component: () => import(/* webpackChunkName: "about" */ '../views/home.vue')
	}
]

const router = new VueRouter({
	mode: 'history',
	base: process.env.BASE_URL,
	routes
})

router.beforeEach((to, from, next) => {
	// to 去哪儿
	// from 从哪儿来
	// next 往下走
	const token = localStorage.getItem('token')
	if (to.path === '/login' || to.path === '/register') {
		// 判断token在不在，如果在，说明不用进入登录页面
		// 如果不在了。进入登录页面，同时要带上回调地址
		if (token) {
			next('/blogs')
		} else {
			next()
		}
	} else {
		if (token) {
			next()
		} else {
			next(`/login?redirect=${to.path}`)
		}
	}
})

export default router
